package com.esdk.sql.orm;

import java.sql.Connection;
import java.util.HashMap;

import com.esdk.esdk;
import com.esdk.sql.SQLRuntimeException;

public class ORMSessionFactory{
	private static final HashMap<Integer,ORMSession> _ormSessions=new HashMap<Integer,ORMSession>();
	public static ORMSession getORMSession(Connection conn){
		synchronized(_ormSessions){
			return esdk.obj.or(_ormSessions.get(conn.hashCode()),()->createORMSession(conn));
		}
	}

	public static ORMSession getORMSession(){
		return getORMSession(ConnectionUtils.getConnection());
	}

	public static ORMSession createORMSession(Connection conn){
		return new ORMSession(conn);
	}

	public static ORMSession createORMSession(){
		return new ORMSession(ConnectionUtils.getConnection());
	}

	static ORMSession addORMSession(ORMSession ormSession){
		synchronized(_ormSessions){
			if(_ormSessions.containsKey(ormSession.conn.hashCode())) {
				throw new SQLRuntimeException("Connection is existed in other ormsession");
			}
			_ormSessions.put(ormSession.conn.hashCode(),ormSession);
			return ormSession;
		}
	}

	public static void closeORMSession(ORMSession ormSession) {
		synchronized(_ormSessions){
			removeORMSession(ormSession);
			ormSession.close();
		}
	}

	public static void removeORMSession(Connection conn){
		if(_ormSessions.containsKey(conn.hashCode())) {
			ORMSession remove=_ormSessions.remove(conn.hashCode());
			remove.clear();
		}
	}
	public static void removeORMSession(ORMSession ormSession){
		synchronized(_ormSessions){
			if(ormSession!=null){
				ormSession.clear();
				_ormSessions.remove(ormSession.conn.hashCode());
			}
		}
	}

	public static void cleanup(){
		synchronized(_ormSessions){
			_ormSessions.clear();
		}
	}

}
